#!/bin/bash

# Copyright (c) 2009-2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Script to build ThreadSanitizer binaries for use with chromium
source common.sh
if system_is_snow_leopard
then
  echo "ThreadSanitizer is not fully supported on Mac OS X 10.6 yet." >&2
  echo "See http://code.google.com/p/data-race-test/issues/detail?id=44" >&2
fi

POST_BUILD_HOOK_DEFINED=yes
post_build_hook() {
  # {{{1
  PLATFORM=$1
  cd "$TSAN_DIR/tsan"

  SPECIAL_TARGET=
  SPECIAL_FLAGS=
  # We can build two target architectures on a Linux x64 machine, so we should
  # a) Use separate output directories,
  # b) Explicitly specify 32-bit linux for x86 build.
  case "$PLATFORM" in
    "linux_x64")
      SPECIAL_FLAGS="OUTDIR=out64"
    ;;
    "linux_x86")
      SPECIAL_FLAGS="OUTDIR=out32"
      SPECIAL_TARGET="l32"
    ;;
  esac

  make -j4 $SPECIAL_FLAGS OFFLINE= PIN_ROOT= \
           VALGRIND_INST_ROOT="$BINARIES_DIR/$PLATFORM" \
           VALGRIND_ROOT="$VG_TSAN_DIR" $SPECIAL_TARGET

  OUT_BIN="$ORIG_BINARIES_DIR/$PLATFORM/bin"
  mkdir -p "$OUT_BIN"
  # See below for the definition of ORIG_BINARIES_DIR
  "$TSAN_DIR/tsan/mk-self-contained-valgrind.sh" \
    "$VG_TSAN_DIR/out/$PLATFORM" "tsan" \
    "$OUT_BIN/valgrind-tsan.sh"
  # }}}
}

switch_gcc_for_darwin() {
  # {{{1
  if ls /opt/local/bin/ | grep "^gcc-mp-4\.4" >/dev/null
  then
    export GCC_BINARY_MASK="/opt/local/bin/XXX-mp-4.4"
    export PATH="$THISDIR/macports-gcc-wrapper:$PATH"
    echo "Using gcc-4.4 from MacPorts to build ThreadSanitizer."
  elif gcc --version | grep " 4\.[0-3]\.[0-9]\| 3\.[0-9]\.[0-9]" >/dev/null
  then
    echo "Your gcc version is older than 4.4."
    echo "It is recommended to use gcc-4.4 from MacPorts for building"
    echo "ThreadSanitizer, especially if you plan to commit binaries into SVN."
    echo "See http://gcc44.darwinports.com/ for getting gcc-4.4"
    echo ""
    echo -n "Do you want to continue using old gcc? (y/N)"
    read CONFIRMATION
    if [ "$CONFIRMATION" != "y" ]
    then
      exit 1
    fi
  fi
  # }}}
}

TSAN_REV=4440
TSAN_DIR="$VG_SRC_DIR/tsan" # Directory to checkout TSan sources
rm -rf "$TSAN_DIR"
svn co -r "$TSAN_REV" http://data-race-test.googlecode.com/svn/trunk "$TSAN_DIR"

# Directory to checkout Valgrind sources
VG_TSAN_DIR="$TSAN_DIR/third_party/valgrind"
# Fetch sources from valgrind-variant
sh "$TSAN_DIR/third_party/update_valgrind.sh"

cd "$VG_TSAN_DIR"

if [ `uname -s` == "Darwin" ]
then
  switch_gcc_for_darwin
fi

# Ugly hack!
# We build Valrgind binaries in the $VG_TSAN_DIR/out and then pack
# them into self-contained .sh file into $ORIG_BINARIES_DIR/$PLATFORM
ORIG_BINARIES_DIR="$BINARIES_DIR"
BINARIES_DIR="$VG_TSAN_DIR/out"
build_valgrind_for_available_platforms
